package xdu.lz.stage7_jucCollection.blockingqueue;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created at 2019/10/28 0028 下午 11:02
 * --
 */
public class PC_SynQueue {
    //同步队列，保证生产一个消费一个
    private static SynchronousQueue<Integer> queue = new SynchronousQueue<>();

    private static AtomicInteger counter = new AtomicInteger(0);

    public void produce(){
        try {

            queue.put(counter.incrementAndGet());
            System.out.println(Thread.currentThread().getName()+"P:"+counter.get());
            Thread.sleep(20);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public void consume(){
        Integer take = null;
        try {
            take = queue.take();
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("C:"+take);
    }

    public static void main(String[] args) {
        PC_SynQueue pattern = new PC_SynQueue();
        for (int i = 0; i < 2; i++) {
            new Thread(()->{
                while (true){
                    pattern.produce();
                }
            },i+"").start();
        }

        for (int i = 0; i < 1; i++) {
            new Thread(()->{
                while (true){
                    pattern.consume();
                }
            }).start();
        }
    }
}
